import { login } from '@/api/user'
import router from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      tokenTime: ''
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      state.tokenTime = Date.now()
    },
    setUserInfo(state, info) {
      state.userInfo = info
    }
  },
  actions: {
    // 登录
    async login(ctx, val) {
      try {
        const res = await login(val)
        console.log(res)
        // 保存Token
        ctx.commit('setToken', res.data.token.token)
        // 保存用户信息
        ctx.commit('setUserInfo', res.data.user)
        router.push('/')
      } catch (error) {
        console.dir(error, val)
      }
    },
    // 退出功能
    logout({ commit }) {
      // 清空token与用户信息
      commit('setToken', '')
      commit('setUserInfo', {})
      router.push('/login')
    }
  }
}
